package project.dwd.wit.ie.tripfinancemanager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import project.dwd.wit.ie.tripfinancemanager.model.Trip;


public class ListTripsActivity extends ActionBarActivity {

    private List<Trip> tripList;
    private ListView listView;
    String[] listTripsString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_trips);
        tripList = new ArrayList<Trip>();

        listView = (ListView) findViewById(R.id.list_trips_listview);

        getAllFiles();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_list_trips, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void getAllFiles() {
        new LoadFiles(this).execute();
    }

    public void updateGui() {
        ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, listTripsString);

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item value
                String  itemValue = (String) listView.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :" + position + "  ListItem : " + itemValue, Toast.LENGTH_LONG)
                        .show();

                startNewActivity(position, tripList.get(position).getFilename(),tripList.get(position).getTripName());

            }

        });
    }

    public void startNewActivity(int position, String filename, String tripName) {
        Intent i = new Intent(this, ExpensesActivity.class);
        i.putExtra("filename", filename);
        i.putExtra("tripName", tripName);
        startActivity(i);
    }


public class LoadFiles extends AsyncTask<Void, Void, File[]> {

    private Activity activity;
    private ProgressDialog dialog;

    public LoadFiles(Activity activity) {
        this.activity = activity;
        dialog = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.dialog.setMessage("Loading files... please wait");
        this.dialog.show();
        Log.e("onPre", "onPreExecute Method called");
    }

    @Override
    protected File[] doInBackground(Void... params) {
        String path = getCacheDir()+"";

        File f = new File(path);
        File file[] = f.listFiles();

        for (int position=0; position < file.length; position++) {
            readFile(file[position].getName());
        }

        return file;
    }

    public String readFile(String filename) {
        String tripName = "";
        //Get the text file
        File file = new File(getCacheDir(),filename);
        //Read text from file
        StringBuilder text = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            //First Line is a Trip Name
            tripName = br.readLine();
            Log.e("TripName AQUIIII... ", tripName);

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
        }
        catch (IOException e) {
            //You'll need to add proper error handling here
        }

        Trip _aTrip = new Trip(filename, tripName, text.toString());
        tripList.add(_aTrip);
        Log.e("uma viagem...", _aTrip.toString());
        Log.e("TRIP NUMBER", "one more added");

        return text.toString();
    }


    @Override
    protected void onPostExecute(File[] file) {
        super.onPostExecute(file);

        listTripsString = new String[tripList.size()];
        for (int i = 0; i < tripList.size(); i++) {
            listTripsString[i] = tripList.get(i).getTripName();
        }

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        updateGui();
        Log.e("Post", "onPostExecute Method called");
    }
}


//    public void testing() {
//        public void onClick(View v) {
//            new Thread(new Runnable() {
//                public void run() {
//                    final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
//                    mImageView.post(new Runnable() {
//                        public void run() {
//                            mImageView.setImageBitmap(bitmap);
//                        }
//                    });
//                }
//            }).start();
//        }
//    }

}
